import axios from "axios";
import router from "../router"
import { Message } from "element-ui"

export function request(config) {
    // 1.创建axios的实例
    const instance = axios.create({
        baseURL: 'http://api_dev.wanxikeji.cn',
        timeout: 5000
    });
    // 2.axios的拦截器
    instance.interceptors.request.use(config => {
        // console.log(config);
        if (localStorage.getItem('token')) {
            config.data.token = localStorage.getItem('token')
        }
        return config
    }, err => {
        // console.log(err);
    })

    // 2.2.响应拦截
    instance.interceptors.response.use(res => {
        if (res.data.code == 3000) {
            Message.error({
                message: res.data.msg,
                onClose: function() {
                    localStorage.removeItem("token");
                    localStorage.removeItem("user");
                    router.replace({ path: '/login' });
                    return false;
                }
            })
        }
        return res.data
    }, err => {
        console.log(err);
    })

    // 3.发送真正的网络请求
    return instance(config)
}

export default request;